<?php
Yii::import("application.logic.admin.accountLogic", true);

class AccountController extends AdminController
{
    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }


    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     *
     * @author Yii Framework
     * @param
     * @return array
     */
    public function accessRules()
    {
        return array (
            array (
                'allow', //allow authenticated user to manage information with database
                'actions'    => array( 'index',
                                       'editpage',
                                       'edit',
                                       'delete',
                                       'save',
                                       'importPage',
                                       'execImport'
                                     ),
                'users'      => array('@'),
                'expression' => 'Yii::app()->user->authority == Account::ADMIN'
            ),
            array (
                'deny', //deny all users
                'users' => array('*'),
            )
        );
    }//End accessRules

    /**
     * Show index page of category manager
     *
     * @author  TuanNguyen
     * @version Created 2013-08-15
     * @param
     * @return  void
     */
    public function actionIndex()
    {
        //init
        $accountLogic = new accountLogic();

        //Set default param for get list of category
        $accountLogic->setIndexParam(true);

        //Get list of category
        $accountLogic->getAccountListWithLimit();

        $this->render(
            'index',
            array(
                'arr_data'         => $accountLogic->accountList,
                'i_totalItem'      => $accountLogic->paramList['dataTotal'],
                'i_amountPerPage'  => $accountLogic->paramList['dataPerPage'],
                'i_currentPage'    => $accountLogic->paramList['page'],
                's_columnLabel'    => $accountLogic->paramList['columnLabel'],
                's_sortMethod'     => $accountLogic->paramList['sortMethod'],
                'i_columnPosition' => $accountLogic->paramList['columnPosition'],
                's_filter'         => $accountLogic->paramList['filter']
            )
        );//End render
    }//End actionIndex


    /**
     * Show Adding page of account manager
     *
     * @author  TuanNguyen
     * @version Created 2013-05-17
     * @param
     * @return  void
     */
    public function actionEditpage()
    {
        //init
        $accountLogic = new accountLogic();

        $this->render(
            'editpage',
            array('isIEBrowser' => $accountLogic->paramList['isIEBrowser'])
        );
    }//End actionEditpage


    public function actionEdit()
    {
        if(isset($_POST["i_key"]) && $_POST["i_key"] > 0)
        {
            $model=$this->loadModel($_POST["i_key"]);

            $this->renderPartial(
                "edit",
                array(
                    'o_account'=>$model,
                    "i_key"=>$_POST["i_key"]
                )
            );
        }
        else 
            $this->renderPartial("edit",array("i_key"=>0));
    }
    
    public function actionSave()
    {
        $model=new Account();
        $model->unsetAttributes();
        
        $model->identification = $_REQUEST["item_key"];
        $model->identity = $_REQUEST["txt_account"];
        $model->password = $_REQUEST["txt_password"];
        $model->authority = $_REQUEST["sl_authority"];
        $model->name = $_REQUEST["txt_name"];
        $model->email = $_REQUEST["txt_email"];
        $model->is_female = $_REQUEST["ra_sex"];
        $model->phone = $_REQUEST["txt_phone"];
        $model->address = $_REQUEST["ta_address"];
        $model->birth = $_REQUEST["d_birth"];
        $model->organization = $_REQUEST["sl_organization"];
        
        //Add record
        if( isset($_REQUEST["item_key"]) && $_REQUEST["item_key"] == 0)
        {
            $model->setIsNewRecord(true);
            if(!$model->save())
            {
                $arr_result = array("error" => json_encode($model->getErrors()));
                exit(json_encode($arr_result));
            }
            else
            {
                $arr_result = array("result" => "Đã thêm thành công");
                exit(json_encode($arr_result));
            }
        }//End if add record
        //Update record
        else
        {
            $model->setIsNewRecord(false);
            if(!$model->save())
            {
                $arr_result = array("error" => json_encode($model->getErrors()));
                exit(json_encode($arr_result));
            }
            else
            {
                $arr_result = array("result" => 1);
                //CJSON::encode($model)
                exit(json_encode($arr_result));
            }
        }//End else
        Yii::app()->end();
    }
    
    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete()
    {
        //$this->loadModel($id)->delete();
        $arr_deleteId     = $_REQUEST["arr_deleteId"];
        
        if(is_array($arr_deleteId) == true) {
        
            $s_where        = "";
            
            foreach ($arr_deleteId as $value) {
                $s_where .= "`identification` = ".$value["value"]." OR ";
            }
        
            $s_where    = substr($s_where, 0, -3);
            
            $command = Yii::app()->db->createCommand("CALL account_06_delete (:in_where)");  
            $command->bindValue("in_where",$s_where);
            $s_result = $command->execute(); 
            
            if( $s_result >= 0) {
                
                $arr_result = array("result" => $s_result);
                exit(json_encode($arr_result));
            }
            else {
                
                $arr_error = array("error" => "Đã có lỗi với quá trình xoá, xin hãy nhấn F5 để thử lại:".$s_result);
                exit(json_encode($arr_error));
            }
        
        } else {
            
            $arr_error = array("error" => "Bạn phải chọn một dòng để xoá.");
            exit(json_encode($arr_error));
        }
    }
}
